import { getFullApproval, getType, getProcessType } from '@/services/flowMine/list';

const FIELD_MAP = { startTime: 'starting_time' };

// 转换为服务端需要的格式，如： start_time asc
const transformOrderBy = (orderBy = '') => {
    const [field = '', order = ''] = orderBy.split('_');
    if (field && order) {
        return `${FIELD_MAP[field]} ${order.split('end')[0]}`;
    }
    return '';
};

export default {
    namespace: 'fullApprovalProcess',
    state: {
        fullApprovalProcess: [],
        total: 0,
        pagination: {
            pageSize: 10,
            current: 1,
            total: 0
        },
        treeSelectDate: [],
        processStatusType: []
    },
    effects: {
        *fetchFullApproval({ payload }, { put, call }) {
            const { orderBy } = payload;
            const response = yield call(getFullApproval, { ...payload, orderBy: transformOrderBy(orderBy) });
            if (response.code === 10000) {
                yield put({
                    type: 'save',
                    payload: {
                        fullApprovalProcess: response.data.rows,
                        total: response.data.total,
                        pagination: {
                            current: response.data.pageNo,
                            pageSize: response.data.pageSize,
                            total: response.data.total
                        }
                    }
                });
            }
        },
        *fetchFormData(_, { put, call, all }) {
            const payload2 = {
                code: 'processStatusType'
            };
            const [fetchType, fetchProcessStatusType] = yield all([call(getType), call(getProcessType, payload2)]);
            if (fetchType.code === 10000) {
                yield put({
                    type: 'save',
                    payload: {
                        treeSelectDate: fetchType.data
                    }
                });
            }
            if (fetchProcessStatusType.code === 10000) {
                yield put({
                    type: 'save',
                    payload: {
                        processStatusType: fetchProcessStatusType.data
                    }
                });
            }
        }
    },
    reducers: {
        save(state, { payload }) {
            return {
                ...state,
                ...payload
            };
        },
        setPagination(state, { pagination }) {
            return {
                ...state,
                pagination
            };
        }
    }
};
